﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Easy.Common
{
     public static class DES
    {
         public static string Encrypt(string encryptString, string key)
         {
             byte[] inputByte = Encoding.ASCII.GetBytes(encryptString);
             byte[] keyByte = Encoding.ASCII.GetBytes(key);
             
             DESCryptoServiceProvider des = new DESCryptoServiceProvider();
             des.Key = keyByte;
             des.IV = keyByte;
             MemoryStream ms = new MemoryStream();
             CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
             cs.Write(inputByte, 0, inputByte.Length);
             cs.FlushFinalBlock();
             return Convert.ToBase64String(ms.ToArray());
         }

         public static string Decrypt(string decryptString, string key)
         {
             byte[] inputByte = Convert.FromBase64String(decryptString);
             byte[] keyByte = Encoding.ASCII.GetBytes(key);

             DESCryptoServiceProvider des = new DESCryptoServiceProvider();
             des.Key = keyByte;
             des.IV = keyByte;

             MemoryStream ms = new MemoryStream();
             CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
             cs.Write(inputByte, 0, inputByte.Length);
             cs.FlushFinalBlock();
             //建立StringBuild对象，CreateDecrypt使用的是流对象，必须把解密后的文本变成流对象  
             StringBuilder ret = new StringBuilder();
             return System.Text.Encoding.ASCII.GetString(ms.ToArray());
         }
    }
}
